/**
 * <b>项目名：</b>hclv-web<br/>
 * <b>包名：</b>com.flea.hclv.service.impl<br/>
 * <b>文件名：</b>HServiceOrderUpdateApplyServiceImpl.java<br/>
 * <b>版本信息：</b>1.0<br/>
 * <b>日期：</b>2018年11月16日 下午4:53:59<br/>
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HServiceOrderMapper;
import com.flea.hclv.model.dao.HServiceOrderUpdateApplyMapper;
import com.flea.hclv.model.dao.HTravelGroupMapper;
import com.flea.hclv.model.entity.HServiceOrder;
import com.flea.hclv.model.entity.HServiceOrderUpdateApply;
import com.flea.hclv.model.entity.HTravelGroup;
import com.flea.hclv.service.HServiceOrderService;
import com.flea.hclv.service.HServiceOrderUpdateApplyService;
import com.flea.hclv.util.HclvDictUtil;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.entity.OrgDept;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @description 订单业务修改申请表
 * @createTime 2018年11月16日 下午4:53:59
 * @modifyTime
 * @author myflea@163.com
 * @version 1.0
 */
@Service
public class HServiceOrderUpdateApplyServiceImpl implements HServiceOrderUpdateApplyService {
    @Autowired
    private HServiceOrderUpdateApplyMapper hServiceOrderUpdateApplyMapper;
    @Autowired
    private HServiceOrderMapper hServiceOrderMapper;
    @Autowired
    private HServiceOrderService hServiceOrderService;
    @Autowired
    private HTravelGroupMapper hTravelGroupMapper;

    @Override
    public ServerResponse<HServiceOrderUpdateApply> addUpdateApply(HttpServletRequest request, String model) throws Exception {
        String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        String userId = FleaOrgUtils.getCurUserUuid(request);

        HServiceOrderUpdateApply entity = JSONObject.parseObject(model, HServiceOrderUpdateApply.class);

        if (entity == null || entity.getServerOrderNo() == null) {
            return ServerResponse.createByErrorMessage("申请修改信息异常，请确认信息");
        }
        HServiceOrder serviceOrder = hServiceOrderMapper.findByOrderNo(entity.getServerOrderNo());
        if (null == serviceOrder) {
            return ServerResponse.createByErrorMessage("申请进行修改的订单不存在，请确认信息");
        }
        String receviedId = null;
        String serviceOrgId = serviceOrder.getServiceOrgId();
        String supperId = serviceOrder.getSupplerOrgId();
        //组团社id与当前用户的id相同，则 接收申请的人的部门为 supperId
        if (serviceOrgId.equals(orgId)) {
            receviedId = supperId;
        } else {
            receviedId = serviceOrgId;
        }

        entity.setReceiveOrgId(receviedId);
        entity.setApplerOrgId(orgId);
        entity.setCreateUser(userId);
        entity.setId(FleaStringUtils.getGenerateUUID());
        entity.setModifyUser(userId);
        entity.setCode(FleaStringUtils.getGenerateUUID());
        entity.setStatus(HConstant.D_HCLV_D_SERVICE_ORDER_UPDATE_ALLPY_STATE_WAIT_HADEL);

        boolean result = false;
        try {
            result = hServiceOrderUpdateApplyMapper.insertSelective(entity) == 1;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        if (!result) {
            return ServerResponse.createByErrorMessage("申请失败，请检查您的申请信息：" + model);
        } else {
            return ServerResponse.createBySuccess("申请成功,等待对方确认", entity);
        }

    }

    @Override
    public ServerResponse<HServiceOrderUpdateApply> updateApplyStatus(HttpServletRequest request, String applyId, String status) throws Exception {
        HServiceOrderUpdateApply oldApply = hServiceOrderUpdateApplyMapper.selectByPrimaryKey(applyId);
        if (null == oldApply) {
            return ServerResponse.createByErrorMessage("该申请不存在");
        }
        String userId = FleaOrgUtils.getCurUserUuid(request);
        oldApply.setStatus(status);
        oldApply.setModifyUser(userId);

        boolean result = hServiceOrderUpdateApplyMapper.updateByPrimaryKeySelective(oldApply) == 1;

        if (!result) {
            return ServerResponse.createByErrorMessage("审批操作失败");
        }

        return ServerResponse.createBySuccessMessage("审批操作成功");
    }

    @Override
    public ServerResponse findRecievedApply(HttpServletRequest request, int curPage, int pageSize,
                                            String orderNo) throws Exception {
        String userOrgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        RowBounds bounds = new RowBounds(curPage, pageSize);
        List<HServiceOrderUpdateApply> pages = hServiceOrderUpdateApplyMapper.findByRevicerAndOrderNo(bounds, orderNo, userOrgId);
        try {
            FleaPage<HServiceOrderUpdateApply> result = new FleaPage<>(pages);
            List<HServiceOrderUpdateApply> newData = coverOrgCodeTOName(pages);
            result.setCurPageData(newData);


            return ServerResponse.createBySuccess(result);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }


    }

    @Override
    public ServerResponse findByApplyerId(HttpServletRequest request, int curPage, int pageSize,
                                          String orderNo) throws Exception {
        String userOrgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        RowBounds bounds = new RowBounds(curPage, pageSize);
        List<HServiceOrderUpdateApply> pages = hServiceOrderUpdateApplyMapper.findByApperAndOrderNo(bounds, orderNo, userOrgId);
        try {
            FleaPage<HServiceOrderUpdateApply> result = new FleaPage<>(pages);
            List<HServiceOrderUpdateApply> newData = coverOrgCodeTOName(pages);
            result.setCurPageData(newData);

            return ServerResponse.createBySuccess(result);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public ServerResponse findByApperId(String appelyId) throws Exception {
        if (StringUtil.isEmpty(appelyId)) {
            return ServerResponse.createByErrorMessage("参数传递非法");
        }

        HServiceOrderUpdateApply apply = hServiceOrderUpdateApplyMapper.selectByPrimaryKey(appelyId);
        if (null == apply) {
            return ServerResponse.createByErrorMessage("该申请不存在");
        }
        String orderNo = apply.getServerOrderNo();
        ServerResponse sr = hServiceOrderService.findByOrderNo(orderNo);
        HServiceOrder order = null;
        if (sr.isSuccess()) {
            order = (HServiceOrder) sr.getData();
            if (null == order) {
                return ServerResponse.createByErrorMessage("该申请所对应的订单已经不存在");
            }


            OrgDept currentUserDept = FleaOrgUtils.getOrgDeptByDeptUuid(apply.getApplerOrgId());
            if (currentUserDept!=null){
                apply.setApplerOrgName(currentUserDept.getDeptName());
            }
            currentUserDept = FleaOrgUtils.getOrgDeptByDeptUuid(apply.getReceiveOrgId());
            if (currentUserDept!=null){
                apply.setReceiverOrgName(currentUserDept.getDeptName());
            }
            HTravelGroup hTravelGroup = hTravelGroupMapper.selectByPrimaryKey(order.getGroupId());
            if (hTravelGroup!=null){
                apply.setTravelGroupName(hTravelGroup.getGroupName());
            }
            apply.setShouldPayment(order.getShouldPayment());
            apply.setActualPayment(order.getActualPayment());
            apply.setPayStatus(order.getPayStatus());
            return ServerResponse.createBySuccess("操作成功", apply);
        } else {
            return ServerResponse.createByErrorMessage(sr.getMessage());
        }


    }

    private List<HServiceOrderUpdateApply> coverOrgCodeTOName(List<HServiceOrderUpdateApply> applys) {
        List<HServiceOrderUpdateApply> newApplys = new ArrayList<>();
        for (HServiceOrderUpdateApply apply : applys
                ) {
            apply.setApplerOrgName(HclvDictUtil.coverOrgCodeToName(apply.getApplerOrgId()));
            apply.setReceiverOrgName(HclvDictUtil.coverOrgCodeToName(apply.getReceiveOrgId()));
            newApplys.add(apply);
        }
        return newApplys;
    }


}
